//
//  WeightHistoryViewController.m
//  WeightLog
//
//  Created by Boky on 4/22/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "WeightHistoryViewController.h"
#import "Weight.h"
#import "WeightLog.h"


@implementation WeightHistoryViewController

@synthesize  weightHistoryArray, persistenceUnit;



 - (void)viewDidLoad {
	 [super viewDidLoad];
	 //Recuperamos los pesos de la base de datos aqui ?
	 self.weightHistoryArray = [NSArray arrayWithObjects:@"Peso 1", @"Peso 2", @"Peso 3", @"Peso 4", @"Peso 5", @"Peso 6", @"Peso 7",nil];

	 // Set up the edit and add buttons.
	 //self.navigationItem.leftBarButtonItem = self.editButtonItem;
	 
	 UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(insertNewObject)];
	 
	 self.navigationItem.rightBarButtonItem = addButton;
	 [addButton release];
	 
	 NSError *error = nil;
	 if (![[[self persistenceUnit] fetchedResultsController] performFetch:&error]) {
		 /*
		  Replace this implementation with code to handle the error appropriately.
		  
		  abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		  */
		 NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		 abort();
	 }
	 
	 
	 
 }

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	self.weightHistoryArray = nil;
}

- (void)dealloc {
	[weightHistoryArray dealloc];
	[persistenceUnit release];
	//[managedObjectContext release];
    [super dealloc];
}


/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[persistenceUnit sections] count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   	id <NSFetchedResultsSectionInfo> sectionInfo = [[persistenceUnit sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	// Configure the cell.
	NSManagedObject *managedObject = [[persistenceUnit fetchedResultsController] objectAtIndexPath:indexPath];
	WeightLog *weightLog = (WeightLog *)managedObject;

	NSString * str = [[[weightLog weight ] value] stringValue];
	str = [str stringByAppendingString:@" Kg - "];
	str = [str stringByAppendingString:[[weightLog timeStamp] description]];
	cell.textLabel.text = str;
    
	//cell.textLabel.text = [self.weightHistoryArray objectAtIndex:indexPath.row];
	
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/



// Override to support editing the table view.
// Lo usamos para eliminar la fila!
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		
		
        // Delete the managed object for the given index path
		NSManagedObjectContext *context = [persistenceUnit managedObjectContext];
		[context deleteObject:[[persistenceUnit fetchedResultsController] objectAtIndexPath:indexPath]];
		
		// Save the context.
		NSError *error = nil;
		if (![context save:&error]) {
			/*
			 Replace this implementation with code to handle the error appropriately.
			 
			 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
			 */
			NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
			abort();
		}
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}



/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
	return NO;
}

#pragma mark -
#pragma mark Add a new object

- (void)insertNewObject {
	
	// Create a new instance of the entity managed by the fetched results controller.
	NSManagedObjectContext *context = [persistenceUnit managedObjectContext];
	NSEntityDescription *entity = [[[persistenceUnit fetchedResultsController] fetchRequest] entity];
	
	//Reemplazo por la entity
	WeightLog *newWeightLog = (WeightLog *)[NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
	Weight *newWeight = (Weight *)[NSEntityDescription insertNewObjectForEntityForName:@"Weight" inManagedObjectContext:context];
	
	// If appropriate, configure the new managed object.
	[newWeight setUnit: @"Kilo"];
	[newWeight setValue: [NSDecimalNumber numberWithInt:200]];
	[newWeightLog setValue:[NSDate date] forKey:@"timeStamp"];
	[newWeightLog setWeight: newWeight];
	
	// Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
		/*
		 Replace this implementation with code to handle the error appropriately.
		 
		 abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
		 */
		NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
		abort();
    }
}
   


// NSFetchedResultsControllerDelegate method to notify the delegate that all section and object changes have been processed. 
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
	// In the simplest, most efficient, case, reload the table view.
	[self.tableView reloadData];
}

/*
 Instead of using controllerDidChangeContent: to respond to all changes, you can implement all the delegate methods to update the table view in response to individual changes.  This may have performance implications if a large number of changes are made simultaneously.
 
 // Notifies the delegate that section and object changes are about to be processed and notifications will be sent. 
 - (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
 [self.tableView beginUpdates];
 }
 
 - (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
 // Update the table view appropriately.
 }
 
 - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
 // Update the table view appropriately.
 }
 
 - (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
 [self.tableView endUpdates];
 } 
 */


@end

